<?php
/**
* @software         [JiJinCMS]
* @author           [上海集锦信息科技有限公司]
* @website          [http://www.jijinweb.com]
* @email            [sunny@jijinweb.com]
**/
namespace app\admin\model;
use think\Model;
use think\facade\Db;
class ImportDataModel{
    public $TmpPath,$tableName,$params,$currentSheet,$excelData,$fieldKey,$fieldName;
    function __construct($params){
        //
        $this->params=$params;
        $this->tableName="cms_".$GLOBALS['model'][$params["modelid"]]['table_name'];
    }
    //检查栏目结构
    public function checkCat_type(){
        $catid=I("post.catid",0,"intval");
        $cat_type=I("post.cat_type");//栏目导入方式
        if($cat_type=="selfCheck"&&!$catid){
            return false;
        }
    }
    //创建表格对像
    public function creatExcelObj(){
        $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        if(strstr($this->params["excel_src"],'.xlsx')){
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        }
        $objPHPExcel = $objReader->load(".".$this->params["excel_src"]);
        $this->currentSheet = $objPHPExcel->getActiveSheet();
    }
    //把表格里的图片保存到服务器，并把具体的路径
    public function saveImg(){
        //先处理图片
        $AllImages= $this->currentSheet->getDrawingCollection();
        $ArrayTmp="";
        foreach($AllImages as $drawing){
            if($drawing instanceof \PHPExcel_Worksheet_MemoryDrawing){
                $image = $drawing->getImageResource();
                $filename=$drawing->getIndexedFilename();
                $XY=$drawing->getCoordinates();
                //把图片存起来
                imagepng($image, $this->TmpPath.$filename);
                //把图片的单元格的值设置为图片名称
                $cell = $this->currentSheet->getCell($XY);
                $cell->setValue($this->TmpPath.$filename);
            }
        }
        //重新获取一下表格数据
        $this->getExcelData();
        //删除第一行字段名
        $data=$this->excelData;
        unset($data[0]);
        $this->excelData=$data;
    }
    //把图片路径字段保存到file表里
    public function saveImgToTable($src,$pubid){
        $fileName=  str_replace($this->TmpPath,"",$src);
        $value['pubid']=$pubid;
        $value['name']=$fileName;
        $value['filepath']=trim($src,".");
        $value['savepath']=date("Ymd");
        $fileName_arr=explode(".",$fileName);
        $value['ext']=$fileName_arr[1];
        $value['size']= filesize($src);
        $value['md5']  = md5_file($src);
        $value['sha1'] = sha1_file($src);
        $value['create_time'] = time();
        //判断文件是否存在
        $where['md5']  = $value['md5'];
        $where['sha1'] = $value['sha1'];
        $isFile=M("file")->where($where)->getField("id");
        if($isFile){
            $value['id'] = $isFile;
            M("file")->save($value);
        }else{
            //压缩图片
            $image=new \Think\Image();
            $image->open($src);
            $image->thumb(200,200);
            $small_path=$this->TmpPath."small_".$fileName;
            $image->save($small_path);
            $value['smallpath']=trim($small_path,"."); 
            M("file")->add($value);            
        }
     
    }
    //获取表格内的数据内容
    public function getExcelData(){
        $data=$this->currentSheet->toArray();
        $this->excelData=$data;
    }
    //分割并提取表格第一行做为字段名称
    public function getFieldName(){
        $fieldName=array();
        $fieldName["id"]="ID";
        $fieldName["catid"]="栏目名称";   
        $data=$this->excelData;
        foreach($data[0] as $key=>$v){
            $field_arr=explode("==",$v);
            $fieldKey[$key]=$field_arr[1];
            $fieldName[$field_arr[1]]=$field_arr[0];
        }
        $fieldName["result_status"]="导入结果";
        unset($data[0]);
        $this->fieldKey=$fieldKey;//返回一个excel下标对应字段名的数组，例：array(0=>title,1=>keywords)
        $this->fieldName=$fieldName;//返回一个根据字段下标，对应字段中文值的数组，例：array('title'=>'标题','keywords'=>'关键字')
        $this->excelData=$data;//返回一个去掉第一行的excel data
    }
    //开始插入数据
    public function StartInsertData(){
        $back_data=array();
        $back_data[]=$this->fieldName;        
        foreach($this->excelData as $v){
            $_POST=array();
            $_POST["id"]=0;
            if($this->params["cat_type"]=="selfCheck"){
                $_POST["catid"]=$this->params["catid"];
            }
            $_POST["pubid"]=make_pubid();
            foreach($v as $key2=>$v2){  
                //如果是栏目字段
                if($this->fieldKey[$key2]=="catid"){
                    //判断栏目的形式，栏目名称|栏目ID                
                    if($this->params["cat_type"]=="catName"){//栏目名称
                        $_POST["catid"]=M("cat")->where(array("name"=>$v2))->getField("catid");
                    }else if($this->params["cat_type"]=="catId"){//栏目ID
                        $_POST["catid"]=intval($v2);
                    }
                    //  
                }else{
                    $_POST[$this->fieldKey[$key2]]=$v2?$v2:"";
                }
                //判断是否为图片路径，如果是图片路径把图片路径存到file表里，便用在文件管理器中查看
                if(strstr($v2,$this->TmpPath)){
                    $this->saveImgToTable($v2,$_POST["pubid"]);
                    $_POST[$this->fieldKey[$key2]]=trim($v2,".");
                }
            }
            //查看catid是否存在
            if(!$_POST["catid"]){
                unset($_POST["pubid"]);
                $_POST["result_status"]="<span style='color:red'>导入失败-缺少catid</span>";    
                $resultData=$_POST;
            }else{            
                //如果遇到重复标题如何处理
                //直接新增(为了减少服务器资源这里就不做重复查询)
                if($this->params["check_title"]=="add"){
                    $resultData=$this->saveAction("add");
                }else{
                    //查看数据是否存在
                    $id=M($this->tableName)->where(array($this->params[check_fieldName]=>$_POST[$this->params[check_fieldName]],"catid"=>$_POST["catid"]))->getField("id");
                    if($id){
                        if($this->params["check_title"]=="update"){
                            $_POST["id"]=$id;
                            $resultData=$this->saveAction("update");
                        }else{
                            unset($_POST["pubid"]);
                            $_POST["result_status"]="<span style='color:red'>导入失败-标题重复</span>";    
                            $resultData=$_POST;
                        }
                    }else{
                        $resultData=$this->saveAction("add");
                    }
                }
            }
            $back_data[]=$resultData;
        }   
        return $back_data;
    }
    //保存操作
    private function saveAction($type){
        //调用模型里的数据插入方式
        if($type=="add"){
            $resultdata=D("Info")->data_add("export");
            $result_status="导入成功（新增）";
        }else{
            $resultdata=D("Info")->data_editor("export");
            $result_status="导入成功==（更新）";
        }
        foreach($this->fieldName as $key=>$v3){
            $newdata[$key]=$resultdata[$key]?$resultdata[$key]:"-";
        }
        $newdata["catid"]=$GLOBALS['cat'][$newdata["catid"]][name];
        $newdata["result_status"]=$result_status;
        return $newdata;
    }
    
    
    
}
